package org.qydjk.console.service.impl;

import org.qydjk.common.dao.IBaseDao;
import org.qydjk.common.pojo.Category;
import org.qydjk.common.service.impl.BaseService;
import org.qydjk.common.util.ListUtil;
import org.qydjk.common.util.StringUtil;
import org.qydjk.common.vo.EasyUIResponse;
import org.qydjk.common.vo.HibernatePage;
import org.qydjk.console.service.ICategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 分类service实现
 * Created by Edward_yang on 2017/12/13 0013.
 */
@Service
public class CategoryService  extends BaseService  implements ICategoryService{
    @Autowired
    private IBaseDao baseDao;
    /****
     * 返回EasyUIResponse的所有查询
     * @author Edward_yang
     * @uptime 2017-12-13
     * @return EasyUIResponse
     */
    public EasyUIResponse findAllCategoryList(Integer page, Integer rows) throws Exception{
            HibernatePage pager = new HibernatePage(page,rows);
            String sql="select * from qy_category qc order by qc.ord desc";
            List<Category>  classifylistList =baseDao.findBySQL(sql, Category.class,pager);
            int total = baseDao.getRecordCountHQL("select count(c.id) from Category c");
            return new EasyUIResponse(total,classifylistList);
    }
    /***
     * 查询所有返回 List
     * @author Edward_yang
     * @uptime 2017-12-13
     * @return List<Category>
     */
    public List<Category> findAllList() throws Exception{
            String sql="select * from qy_category qc order by qc.ord desc";
            List<Category>  classifylistList =baseDao.findBySQL(sql, Category.class);
            return classifylistList;
    }

    /**
     * 根据叶子节点的ids查找所有的包含自己的父节点的ids
     * @param leafIds
     * @return
     * @throws Exception
     */
    public String findAllByLeafIds(String leafIds) throws Exception {
        String[] ids = new String[]{};
        List<Category> cats = baseDao.findByHql("from Category c where c.id in (" + leafIds + ")");
        for(Category cat: cats){
            String catIds = cat.getParentIdAll();
            if(!StringUtil.isEmptyOrNull(catIds)){
                String[] catArr = catIds.split(",");
                ids = (String[]) ListUtil.arrCombine(ids,catArr);
            }
        }
        String catIds = ListUtil.wipeRepeat(ids);
        return catIds;
    }

    /**
     * 排除所有父节点的ids
     * @param callIds
     * @return
     * @throws Exception
     */
    public String findAllNoParentCatIds(String callIds) throws Exception {
        List<Category> cats = baseDao.findByHql("from Category c where c.id in (" + callIds + ") and c.isLeaf = ?",1);
        StringBuffer catIdsSB = new StringBuffer();
        for(Category cat: cats){
            catIdsSB.append(cat.getId().intValue()).append(",");
        }
        String catIds = StringUtil.dotWipeStartEnd(catIdsSB.toString());
        return catIds;
    }

    /**
     * 保存分类,更新父节点为非叶子节点
     */
    public void saveCategoryAndUpdateParentLeaf(Category category) throws Exception {
        category.setIsLeaf(1);
        String parentIdAll = findCategoryParentIdAllById(category.getParentId());
        baseDao.save(category);
        if(StringUtil.isEmptyOrNull(parentIdAll)){
            category.setParentIdAll(String.valueOf(category.getId()));
        }else {
            category.setParentIdAll(parentIdAll + "," + category.getId());
        }
        baseDao.update(category);
        if (category.getParentId() != null) {
            Category parentCategory = baseDao.get(Category.class, category.getParentId());
            if (parentCategory.getIsLeaf() == 1) {
                parentCategory.setIsLeaf(0);
                baseDao.saveOrUpdate(parentCategory);
            }
        }
    }

    /**
     * 编辑分类,判断是否需要更新父节点叶子状态
     */
    public void updateCategoryAndUpdateParentLeaf(Category category, Integer parentId) throws Exception {
        String parentIdAll = findCategoryParentIdAllById(category.getParentId());
        if(StringUtil.isEmptyOrNull(parentIdAll)){
            category.setParentIdAll(String.valueOf(category.getId()));
        }else {
            category.setParentIdAll(parentIdAll + "," + category.getId());
        }
        baseDao.update(category);
        //检查原父节点是否变为叶子节点
        List<Category> parentCategoryList = baseDao.findByHql("FROM Category a WHERE a.parentId = " + parentId);
        if (ListUtil.isNullOrEmpty(parentCategoryList)) {
            Category parentCategory = baseDao.get(Category.class, parentId);
            parentCategory.setIsLeaf(1);
            baseDao.saveOrUpdate(parentCategory);
        }
        //新父节点变更为非叶子节点
        if (category.getParentId() != null) {
            Category parentCategory = baseDao.get(Category.class, category.getParentId());
            if (parentCategory.getIsLeaf() == 1) {
                parentCategory.setIsLeaf(0);
                baseDao.saveOrUpdate(parentCategory);
            }
        }
    }

    /**
     * 刪除分类时如果父节点不包含子节点,修改父节点为叶子节点
     *
     * @param category
     */
    public void deleteCategoryAndUpdateParentLeaf(Category category) throws Exception {
        Category categoryInfo = baseDao.get(Category.class, category.getId());
        baseDao.delete(categoryInfo);
        List<Category> parentCategoryList = baseDao.findByHql("FROM Category a WHERE a.parentId = " + categoryInfo.getParentId());
        if (ListUtil.isNullOrEmpty(parentCategoryList)) {
            Category parentCategory = baseDao.get(Category.class, categoryInfo.getParentId());
            parentCategory.setIsLeaf(1);
            baseDao.saveOrUpdate(parentCategory);
        }
    }

    /**
     * 递归查询id
     * @param id
     * @return
     * @throws Exception
     */
    public String findCategoryParentIdAllById(Integer id) throws Exception {
        if (id != null) {
            Category category = baseDao.get(Category.class, id);
            String pid = String.valueOf(category.getId());
            Integer parentId = category.getParentId();
            if (parentId != null) {
                String pidIn = findCategoryParentIdAllById(parentId);
                pid = pidIn + "," +  pid;
                return pid;
            } else {
                return pid;
            }
        } else {
            return "";
        }
    }
}
